package cn.et;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;
public class IndexDemo {	
	static String drc="E:\\index";
	//定义存储目录
	static Analyzer aly= new IKAnalyzer();
	public static void main(String[] args) throws Exception {
		search();	
	}
	//搜索
	public static void search() throws Exception {
		Directory dr= FSDirectory.open(new File(drc));
		//读取存储目录
		DirectoryReader ird=DirectoryReader.open(dr);
		//搜索类
		IndexSearcher isearcher=new IndexSearcher(ird);
		//Lucene查询解析 用于指定查询的属性名和分词器
		QueryParser parser = new QueryParser(Version.LUCENE_47,"userDesc", aly);
		//开始搜索
		Query query=parser.parse("来");
		//获取搜索的结果指定返回的docuemnt个数
		ScoreDoc[] hits= isearcher.search(query, null, 10).scoreDocs;
		for(int i=0;i<hits.length;i++){
			//获取单独的document
			Document hitDoc = isearcher.doc(hits[i].doc);
			System.out.println(hitDoc.getField("userName").stringValue());
		}
			ird.close();
			dr.close();
	}
	//创建索引库
	public static void write() throws IOException{
		//索引库的存储目录
		Directory dr= FSDirectory.open(new File(drc));
		//管联Lucene版本和当前分词器
		IndexWriterConfig cfi= new IndexWriterConfig(Version.LUCENE_47,aly);
		//传入目录和分词器
		IndexWriter iwriter = new IndexWriter(dr,cfi);
		//document对象Field属性
		Document doc= new Document();
		//TextField.TYPE_STORED 写入存储目录
		Field field= new Field("userName","张三",TextField.TYPE_STORED);
		 doc.add(field);
		 field= new Field("userDesc","张三来自永州，喜欢吃永州血鸭",TextField.TYPE_STORED);
		 doc.add(field);
		 Document doce= new Document();
			//TextField.TYPE_STORED 写入存储目录
			Field field1= new Field("userName","李四",TextField.TYPE_STORED);
				doce.add(field1);
			 field1= new Field("userDesc","李四来自北京，喜欢吃烤鸭",TextField.TYPE_STORED);
			 doce.add(field1);
		 //写入存储目录
		 iwriter.addDocument(doc);
		 iwriter.addDocument(doce);
		 iwriter.commit();
		 iwriter.close();
	}
}
